﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Net;
using System.IO;

namespace Halfwit
{
    public interface IPlugin
    {
        string Id { get; }
        string Name { get; }
        string Protocol { get; }
        string Description { get; }
    }

    public interface IUrlShortener : IPlugin
    {
        string Shorten(string Url);

        /// <summary>
        /// Not used
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        string Expand(string Url);
    }

    public class IsGd : IUrlShortener
    {
        private const string APIUrl = "http://is.gd/api.php?longurl=";

        public string Id { get { return Name; } }

        public string Name { get { return "is.gd"; } }

        public string Expand(string url) { return url; }
        
        public string Protocol { get { return "is.gd"; } }

        public string Description { get { return "is.gd is a service that shortens URLs such as web addresses. Our goal is to allow shortening URLs to the maximum extent technically possible."; } }

        public string Shorten(string url)
        {
            try
            {
                var request = WebRequest.Create(APIUrl + url);
                var res = request.GetResponse();
                string text;

                using (var reader = new StreamReader(res.GetResponseStream()))
                {
                    text = reader.ReadToEnd();
                }
                return !string.IsNullOrEmpty(text) ? text : url;
            }
            catch
            {
                return url;
            }
        }
    }
}
